<script lang="ts" setup>
import dayjs from 'dayjs';
import { format } from 'date-fns';

const props = defineProps({
	cont: Object,
	contractProductId: Number,
});
const username = useCookie('username');
const urlHome = useUrl();
const isOpen = ref(false);
const fondList = ref([
	{ label: 'Фонд оплаты', value: 0, disabled: true },
	{ label: 'ОМС', value: 'oms' },
	{ label: 'ОБ', value: 'ob' },
	{ label: 'ПД', value: 'pd' }]);
const docType = ref([
	{ label: 'Тип документа', value: 0, disabled: true },
	{ label: 'Приход', value: '1' },
	{ label: 'Расход', value: '2' },
]);
const typeDocSelect = ref<string | number>(0);
const fond = ref<string | number>(0);
const income = ref<string | number>('');
const outcome = ref<string | number>('');
const docDate = ref(new Date());
const incomingDocument = ref('');

async function addDocument() {
	income.value = '';
	outcome.value = '';
	isOpen.value = true;
}

const fondComputed = computed(() => typeDocSelect.value === '1' ? fond.value : 'out')

interface IContractProduct {
	id: number
	contract: {
		id: number
		organization_name: string
		contract_number: string
		is_closed: boolean
		start_date: Date
		end_date: Date
		is_active: boolean
	}
	oms_full: number
	oms_balance: number
	oms_percent: number
	ob_full: number
	ob_balance: number
	ob_percent: number
	pd_full: number
	pd_balance: number
	pd_percent: number
	product: {
		id: number
		name: string
		measure: string
		warehouse: number
	}
}

const { data: contractProduct, refresh: contractProductRefresh, status: contractProductStatus } = await useFetch<IContractProduct>(`${urlHome.value}orders/product_contract/`, {
	query: {
		contract_product_id: props.contractProductId
	}
})


async function commitDocument() {
	// if ((income.value >= 0 && ['oms', 'ob', 'pd'].includes(fond.value)) || (outcome.value >= 0 && fond.value === 'out')) {
	if (income.value === '') {
		income.value = 0;
	}
	if (outcome.value === '') {
		outcome.value = 0;
	}

	const response = await $fetch(`${urlHome.value}orders/add_stock/`, {
		method: 'POST',
		body: {
			contract_product_id: contractProduct?.value?.id,
			income: income.value,
			outcome: outcome.value,
			fond: fondComputed.value,
			username: username.value,
			document_date: dayjs(docDate.value).format('YYYY-MM-DD'),
			incoming_document: incomingDocument.value,
		},
	})
	if (response) {
		isOpen.value = false;
		ordersListRefresh();
		contractProductRefresh();
	} else {
		console.log("commitDocument error: ", response)
	}
}

interface OrdersSchema {
	id: number
	document_date: Date
	incoming_weight: number
	outgoing_weight: number
	incoming_document: string
}

interface OrdersFull {
	oms_docs: OrdersSchema[] | null
	ob_docs: OrdersSchema[] | null
	pd_docs: OrdersSchema[] | null
	out_docs: OrdersSchema[] | null

}

const { data: ordersList, status: ordersListStatus, refresh: ordersListRefresh } = await useFetch<OrdersFull>(`${urlHome.value}orders/orders_list/`, {
	query: {
		contract_id: contractProduct?.value?.id,
	}
})

const outOutgoingMessage = computed(() => fond.value === 'out' && typeof outcome.value === 'number' && contractProduct.value && outcome.value > contractProduct.value.product.warehouse ? `Вы не можете выписать больше остатка на складе: ${contractProduct.value.product.warehouse}` : '')

const isDisabledCommit = computed(() => omsIncomeMessage.value === '' && obIncomeMessage.value === '' && pdIncomeMessage.value === '' && typeof income.value === 'number' && income.value >= 0 && typeof fond.value === 'string' && ['oms', 'ob', 'pd'].includes(fond.value) ? false : true)
const isDisabledOutcomeCommit = computed(() => outOutgoingMessage.value === '' && typeof outcome.value === 'number' && outcome.value >= 0 && fond.value === 'out' ? false : true)

const omsIncomeMessage = computed(() => fond.value === 'oms' && typeof income.value === 'number' && contractProduct.value && income.value > contractProduct.value.oms_balance ? `Вы не можете выписать больше остатка по договору: ${contractProduct.value.oms_balance}` : '')
const obIncomeMessage = computed(() => fond.value === 'ob' && typeof income.value === 'number' && contractProduct.value && income.value > contractProduct.value.ob_balance ? `Вы не можете выписать больше остатка по договору: ${contractProduct.value.ob_balance}` : '')
const pdIncomeMessage = computed(() => fond.value === 'pd' && typeof income.value === 'number' && contractProduct.value && income.value > contractProduct.value.pd_balance ? `Вы не можете выписать больше остатка по договору: ${contractProduct.value.pd_balance}` : '')


watchEffect(() => {
	console.log(isOpen.value)
	if (isOpen.value === false) {
		typeDocSelect.value = 0;
	}
})

watchEffect(() => {
	console.log(typeDocSelect.value)
	if (typeDocSelect.value === '2') {
		fond.value = 'out';
	}
})

async function rerender() {
	contractProductRefresh();
	ordersListRefresh();

}

</script>
<template>
	<UAlert title="Customize Alert Avatar" description="Insert custom content into the avatar slot!" :avatar="{
		src: 'https://xenonshop22.ru/upload/medialibrary/dcd/xrd2qta5zudhs3jel5d9uler2wyvn8m5.png',
		alt: 'Договор'
	}">
		<template #title="{ title }">
			{{ contractProduct?.contract.organization_name }}
		</template>
		<template #description="description">
			Договор №{{ contractProduct?.contract.contract_number }} с {{
				dayjs(contractProduct?.contract.start_date).format('DD.MM.YYYY')
			}} по {{ dayjs(contractProduct?.contract.end_date).format('DD.MM.YYYY') }}
			<UButton label="Добавить документ" @click="addDocument" />
		</template>
	</UAlert>
	<div class="px-2 font-bold text-xl text-green-600">Остаток на складе: {{ contractProduct?.product.warehouse }} {{
		contractProduct?.product.measure }}
	</div>
	<div class="flex flex-row sm:max-xl:flex-col justify-around gap-4 text-center">
		<div class="xl:basis-1/3">
			<div class="flex flex-col">
				<div class="font-bold">ОМС</div>
				<PbStockProgress :balance="contractProduct?.oms_balance" :percent="contractProduct?.oms_percent"
					:fullPrice="contractProduct?.oms_full" />

				<PbStockOutput :contract_id="contractProduct?.id" :stock_code="`oms`"
					:product_id="contractProduct?.product?.id" :balance="contractProduct?.oms_balance"
					:ordersList="ordersList?.oms_docs" :ordersListRefresh="ordersListRefresh"
					:contractProductRefresh="contractProductRefresh" />
			</div>
		</div>
		<div class="xl:basis-1/3">
			<div class="flex flex-col">
				<div class="font-bold">ОБ</div>
				<PbStockProgress :balance="contractProduct?.ob_balance" :percent="contractProduct?.ob_percent"
					:fullPrice="contractProduct?.ob_full" />
				<PbStockOutput :contract_id="contractProduct?.id" :stock_code="`ob`"
					:balance="contractProduct?.ob_balance" :product_id="contractProduct?.product.id"
					:ordersList="ordersList?.ob_docs" :ordersListRefresh="ordersListRefresh"
					:contractProductRefresh="contractProductRefresh" />
			</div>
		</div>
		<div class="xl:basis-1/3">
			<div class="flex flex-col">
				<div class="font-bold">ПД</div>
				<PbStockProgress :balance="contractProduct?.pd_balance" :percent="contractProduct?.pd_percent"
					:fullPrice="contractProduct?.pd_full" />
				<PbStockOutput :contract_id="contractProduct?.id" :stock_code="`pd`"
					:balance="contractProduct?.pd_balance" :product_id="contractProduct?.product.id"
					:ordersList="ordersList?.pd_docs" :ordersListRefresh="ordersListRefresh"
					:contractProductRefresh="contractProductRefresh" />
			</div>
		</div>
		<div class="xl:basis-1/3">
			<div class="flex flex-col">
				<div class="font-bold">Расход</div>
				<PbStockProgress :balance="contractProduct?.product.warehouse" :percent="100"
					:fullPrice="contractProduct?.product.warehouse" />
				<PbStockOutgoing :contract_id="contractProduct?.id" :stock_code="`out`"
					:balance="contractProduct?.pd_balance" :product_id="contractProduct?.product.id"
					:ordersList="ordersList?.out_docs" :ordersListRefresh="ordersListRefresh"
					:contractProductRefresh="contractProductRefresh" />
			</div>
		</div>
	</div>
	<UModal v-model="isOpen">
		<div class="p-4">
			<USelect v-model="typeDocSelect" :options="docType" value-attribute="value" />
		</div>
		<div v-if="typeDocSelect === '1'">
			<div class="p-4 flex flex-col gap-2">
				<label class="label">
					<span class="label-text ">Фонд оплаты</span>
				</label>
				<USelect v-model="fond" :options="fondList" value-attribute="value" />
				<label class="label">
					<span class="label-text ">Приход:</span>
				</label>
				<div class="font-bold text-red-500">{{ omsIncomeMessage }}{{ obIncomeMessage }}{{ pdIncomeMessage }}
				</div>
				<UInput v-model.number="income" label="Приход" />
				<label class="label">
					<span class="label-text ">Документ прихода:</span>
				</label>
				<UInput v-model=incomingDocument label="Документ прихода" />
				<div class="flex flex-row gap-2">
					<label>Дата документа:</label>
					<UPopover :popper="{ placement: 'bottom-start' }">
						<UButton icon="i-heroicons-calendar-days-20-solid" :label="format(docDate, 'd.MM.yyy')" />

						<template #panel="{ close }">
							<DatePicker v-model="docDate" is-required @close="close" />
						</template>
					</UPopover>
				</div>
				<UButton size="lg" label="Сформировать документ" @click="commitDocument" :disabled="isDisabledCommit" />
			</div>
		</div>
		<div v-else-if="typeDocSelect === '2'">
			<div class="p-4 flex flex-col gap-2">
				<label class="label">
					<span class="label-text ">Расход:</span>
				</label>
				<div class="font-bold text-red-500">{{ outOutgoingMessage }}
				</div>
				<UInput v-model.number="outcome" label="Расход" />
				<div class="flex flex-row gap-2">
					<label>Дата документа:</label>
					<UPopover :popper="{ placement: 'bottom-start' }">
						<UButton icon="i-heroicons-calendar-days-20-solid" :label="format(docDate, 'd.MM.yyy')" />
						<template #panel="{ close }">
							<DatePicker v-model="docDate" is-required @close="close" />
						</template>
					</UPopover>
				</div>
				<UButton size="lg" label="Сформировать документ" @click="commitDocument"
					:disabled="isDisabledOutcomeCommit" />
			</div>
		</div>

	</UModal>
</template>